﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AsPlugInManager;
using AsLib;
using System.Globalization;

namespace NNLInterface
{
    public partial class frmOrderImport : NNLInterface.frmBaseBasic
    {

        #region 初始化



        string strSQLHead = " select cast(1 as bit) as chkSelect , * from vie_OrdersIn ";
        string strTranNo = "";

        public frmOrderImport()
        {
            InitializeComponent();
            this.Load += new EventHandler(frmOrderImport_Load);

        }

        public frmOrderImport(IASPArgList argList)
        {
            InitializeComponent();
            common.agrs = (ASPArgList)argList;
            this.Load += new EventHandler(frmOrderImport_Load);
            this.lokDepart.EditValueChanged += new EventHandler(lokDepart_EditValueChanged);
            this.lokDepart.ProcessNewValue += new DevExpress.XtraEditors.Controls.ProcessNewValueEventHandler(lokDepart_ProcessNewValue);
            this.ListGrid.MouseDown += new MouseEventHandler(ListGrid_MouseDown);
        }

        void frmOrderImport_Load(object sender, EventArgs e)
        {
            //new ChineseLanguage.Chinese();   
            this.SowCheckBox = true;

           
            //如果当前工程下的用户名为空，则提示输入
            if (common._userid == "")
            {
                frmLogon frmLog = new frmLogon();
                frmLog.ShowDialog();

                if (frmLog.DialogResult == DialogResult.OK)
                {
                    frmLog.Dispose();
                    frmLog = null;
                }
                else
                {
                    this.Close();
                    return;
                }

            }

            IniDataSource();


        }

        private void frmOrderImport_FormClosing(object sender, FormClosingEventArgs e)
        {
          
            serial.SerializeBinary(common.sysParameter, Application.StartupPath + @"\NNLInterface.dat");
            common._its_accessdb = null;
            common.pro = null;
            GC.Collect();
        }


        private void IniDataSource()
        {
            this.txtUser.Text = common._userid;
            this.txtUserName.Text = common._username;
            this.txtDeptNo.Text = common._DeptNo;
            this.txtDeptName.Text = common._DeptName;

            //设定部门的数据源
            SetDeptDataSource();
            this.dteFrom.Text = System.DateTime.Now.AddDays(-common.sysParameter.PreDays).ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);

            string strSQL = strSQLHead + " where 1=2";
            common.SubShowList(accessdb.GetRecord(strSQL).ADODataRst, this.ListGrid, this.ListView, false);
            common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
            this.ListView.Columns[0].OptionsColumn.AllowEdit = true;

            common.GetResourceString(this, this.Name);
            common.RestoreFormLayOut(this, this.layOut, this.grpHead);
            common.ReStoreLayOut(this.ListView);
            this.SetToolVisible(common.ToolVisible.ImportData);
            this.logButtonVisibility = false;


        }
        #endregion

        #region Grid选择按钮

        private void ListGrid_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                DoShowMenu(this.ListView.CalcHitInfo(new Point(e.X, e.Y)));
        }

        void DoShowMenu(DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hi)
        {

            if (hi.HitTest == DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitTest.ColumnButton)
            {
                common.subSelectData(ListGrid, ListView);
            }
        }
        #endregion

        #region 控件变化事件


        private void SetDeptDataSource()
        {
            string strSQL = "SELECT DepartNo,DeptName FROM vie_SysUserDepartMent vsudm WHERE vsudm.UserId='" + this.txtUser.Text + "'";
            this.lokDepart.Properties.DataSource = accessdb.GetRecord(strSQL).ADODataRst;


        }

        void lokDepart_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
           lookupeditProcess.LookUpEditProcessNewValue(sender, ref e);
            
        }

        void lokDepart_EditValueChanged(object sender, EventArgs e)
        {
            if (this.lokDepart.Text != "")
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
            else
                this.txtDepartName.Text = "";
        }

        private void lokDepart_TextChanged(object sender, EventArgs e)
        {
            if (this.lokDepart.Text != "")
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
            else
                this.txtDepartName.Text = "";
        }
        #endregion

        #region 工具栏按钮事件

        private void frmOrderImport_ToolButtonClick(object sender, string e)
        {
            try
            {
                switch (e)
                {
                    case "search":
                        if (this.lokDepart.Text == "")
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("最终部门不能为空，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        if (System.Convert.ToDateTime(dteFrom.Text).AddDays(common.sysParameter.PreDays)>System.DateTime.Now)
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("为保证订单数据的完整性，接单开始日期必须在当前日期前" + common.sysParameter.PreDays.ToString() + "天!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        if(!GetDataFromERP()) return;
                        Cursor currentCursor = Cursor.Current;

                        Cursor.Current = Cursors.WaitCursor;

                        common.SubShowList(SearchData(), this.ListGrid, this.ListView, false);
                        common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
                        this.ListView.Columns[0].OptionsColumn.AllowEdit = true;
                        this.ListGrid.Tag = 1;
                        common.ReStoreLayOut(this.ListView);
                        Cursor.Current = currentCursor;
                        break;
                    case "import":
                        subExportData();
                        break;
                    case "excel":
                        subExportXLS();
                        break;
                    case "print":
                        common.PrintView(this.ListGrid, "工单数据");
                        break;
                    case "exit":
                        common.SaveFormLayOut(this, this.layOut, this.grpHead);
                        common.SaveLayout(this.ListView);
                        this.Dispose();
                        break;
                    default:
                        {
                            break;
                        }
                }


            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private bool GetDataFromERP()
        {
            try
            {
                //取得最大的批次号
                string strDeptNo = lokDepart.Text;
                strTranNo=Convert.ToString( accessdb.GetField("SELECT   '" + strDeptNo + "' + replace(dbo.GetShortDate(GETDATE()),'-','')"));
                strTranNo = Convert.ToString(accessdb.ExecuteSP("pro_GetMaxNoteNo", common.Choose.HasAOutput, new object[] { strTranNo, 3, "ORDERIN", strTranNo }));

                //根据查询条件从ERP中写入数据

                //2013-07-04如果部门为制5，则需要将制5课的ERP工单数据关联物料模型中的数据，得到物料最终交货期，关联【ERP制令复期】和【理论复期】
                //此处理过程在制5课的MO接口视图中已处理，关联的是物料数据库中的视图vie_ErpZ5letyx，改变视图中的WW字段的值


                //取得ERP数据库名称
                string erpDataBase=common.sysParameter.ErpDataBase;

                //通过部门编号的最后一位确定最终部门的范围
                string strPDep = this.lokDepart.Text;
                strPDep = strPDep.Substring(strPDep.Length - 1, 1);

                string strSQL = "INSERT INTO OrdersIn(Code, RecType, ItemCode, EST, LET, Qty, CustomerCode, "
                              + "  Comments, Spec1Code,Spec2Code, NumSpec1,OrderUser_UEST1, "
                              + "  OrderUser_UEST2, OrderUser_UEST3, OrderUser_UEST4, "
                              + "  OrderUser_UEST5,OrderUser_UCLET, StartBuffer, OrderUser_UCDLET, "
                              + "  OrderUser_UBOM,tranno,EntUser,EntDate,spec4code,OrderUser_UCODR,NumSpec2,OrderUser_UCustLET,CustMaterialFlag,Qty_Chk) "
                              + " SELECT ml.MO_NO,'M',ml.MRP_NO,ml.R6,ml.WW,ml.QTY,ml.CUS_NO,ml.RR, "
                              + " cast(ml.SPC AS VARCHAR(2000)) ,ml.DEP,ml.OS_QTY,ml.R61, ml.R62, ml.R63, ml.R64, ml.R65, "
                              + " ml.NEED_DD,ml.mo_DD,ml.EE,ml.ID_NO,'" + strTranNo + "','"
                              + common._userid
                              + "', getdate() ,'" + strTranNo + "', CUS_OS_NO,QTY1,AB,AC,Qty_Chk "
                              + " FROM  " + erpDataBase + ".dbo.MO_LIST ml "
                              //部门选择条件
                              + " where (SUBSTRING( ml.DEP,2,1) in " +  common.GetLanguageWord("OrderImport",strDeptNo) 
                              + " OR SUBSTRING(ml.DEP,4,1)      in " +  common.GetLanguageWord("OrderImport",strDeptNo) + ")";

                if (txtorderNo.Text != "")
                {
                    strSQL += "  and  MO_NO like '%" + this.txtorderNo.Text + "%' ";

                }


                if (txtProductNo.Text != "")
                {
                    strSQL += "  and  MRP_NO like '%" + this.txtProductNo.Text + "%' ";
                }

                if (dteFrom.Text != "")
                {
                    strSQL += "  and  CONVERT(VARCHAR(10),chg_dd,120) >='" + this.dteFrom.Text + "' ";
                }


                if (dteTo.Text != "")
                {
                    strSQL += "  and   CONVERT(VARCHAR(10),chg_dd,120)<='" + this.dteTo.Text + "' ";
                }

                if (!accessdb.RsChange(strSQL)) return false ;

                return true;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void subPrint()
        {
            if (!common.CheckExistsData(this.ListView)) return;
            common.PrintView(this.ListGrid, "工单数据");
        }

        private void subExportXLS()
        {
            try
            {
                if (!common.CheckExistsData(this.ListView)) return;
                common.ExportExcel(this.ListView);
                return;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private DataTable SearchData()
        {
            DataTable dt = new DataTable();
            string strSQL = strSQLHead + "   where TranNo='" + strTranNo + "'";

            dt = accessdb.GetRecord(strSQL).ADODataRst;
            return dt;
        }

        private void subExportData()
        {
            Cursor currentCursor = Cursor.Current;
            int recCount = 0;
            int importFlag = 0;
            string remark = "";

            try
            {
                if (!common.CheckExistsData(this.ListView)) return;
                common.UpdateListView(this.ListView);
                DataTable viewt = (DataTable)this.ListGrid.DataSource;
                DataRow[] drs = viewt.Select("chkSelect=1");
                string strSqlInsert = " set xact_abort on begin tran "
                                     + "  delete from OrdersInTmp; " + "\r\n"
                                     + "  insert into OrdersInTmp select * from ordersin where itemid in(";
                if (drs.Length < 1)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("请至少选择一笔数据!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    if (DevExpress.XtraEditors.XtraMessageBox.Show("确定要将所选择数据导入Asprova中吗(Y/N)?", common.sysParameter.MessageInf, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return;
                    //判断如果有其他的的用户导入,如果SysProSwitch中的开关为真，则不能时行导入
                    string strCheck = "SELECT * FROM SysProSwitch sps WHERE sps.ProcessType='PlanExport' AND sps.OperationProcess=1";

                    if(accessdb.GetRecord(strCheck).RecordNumber>=1)
                    {
                    	DevExpress.XtraEditors.XtraMessageBox.Show("其他用户正在使用导入功能，请稍后再试!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;

                    }

                    Cursor.Current = Cursors.WaitCursor;

                    //将正在导入的状态置为1
                  string  strSqlInsertS = " UPDATE sps SET sps.OperationProcess = 1 FROM SysProSwitch sps "
                                   + " WHERE sps.ProcessType='OrderImport'  ";
                   
                   accessdb.RsChange(strSqlInsertS);

                    //将要删除的订单数据导出，原始订单不为空的数据

                    string stritemid = "";
                    for (int row = 0; row < drs.Length; row++)
                    {
                        stritemid += drs[row]["itemid"].ToString() + ",";
                    }
                    stritemid = stritemid.Substring(0, stritemid.Length - 1);
                    strSqlInsert += stritemid + ")      ";

                    //如果备注1为“Z”暂停生产，或都标识为K,复期和客供复期有一个为空，非分派对象标识为1,
                    strSqlInsert += "  UPDATE oit SET oit.[Disabled] = 1 FROM OrdersInTmp oit WHERE  oit.Spec2Code not like '%5%' and "
                                   + " (oit.CustMaterialFlag='Z'    OR oit.CustMaterialFlag='P'  OR ( oit.CustMaterialFlag='K' AND  (not (isnull(oit.OrderUser_UCustLET,'')<>'' AND "
                                   + " isnull(oit.est,'')<>''))))\n ";
               
                    
                    //更新临时表的标识
                    strSqlInsert += " UPDATE oit SET  oit.StatusFlagExt = 'M',oit.FlagDate = GETDATE() FROM OrdersInTmp oit WHERE oit.TranNo='" + this.strTranNo + "' "
                                   +" commit tran";
                    //Form1 frm1 = new Form1(strSqlInsert);
                    //frm1.ShowDialog();
                    bool status = accessdb.RsChange(strSqlInsert);
                    if (!status) return;
                    bool ExStatus = false;

                    //导入之前，需要将原始的订单的数据保留
                    AsLib.ASBOrder rootOrder = common.pro.RootOrder;
                    AsLib.ASBOrder orderTmp;
                    common.orderFiled[] orderData = new common.orderFiled[rootOrder.ChildCount+1];

                    //保留之前的数据,以下字段导入时不用外部字段来更新
                    for (int i = 1; i <= rootOrder.ChildCount; i++)
                    {
                        orderTmp = (AsLib.ASBOrder)rootOrder.get_ChildAsOrder(i);
                        orderData[i].orderCode =orderTmp.Code;
                        orderData[i].orderDisabled=orderTmp.Disabled?1:0;
                        orderData[i].orderNumSpec3 = orderTmp.NumSpec[3];
                        orderData[i].orderPriority = orderTmp.Priority;
                        orderData[i].orderProductionFactor = orderTmp.ProductionFactor;
                        orderData[i].Comment = orderTmp.get_Comment(1)==null?"":orderTmp.get_Comment(1).ToString();
                    }

                    ExStatus = common.subImportToAsprova("Orders", "ImportOrderToAsprova", "TranNo='" + this.strTranNo + "'");

                    //更新数据
                    rootOrder = common.pro.RootOrder;
                    for (int i = 1; i <= rootOrder.ChildCount; i++)
                    {
                        orderTmp = (AsLib.ASBOrder)rootOrder.get_ChildAsOrder(i);
                        string strCode = orderTmp.Code;
                        for (int j = 0; j < orderData.Length; j++)
                        {
                            if (strCode==orderData[j].orderCode)
                            {
                                orderTmp.Disabled = orderData[j].orderDisabled==1?true:false ;
                                orderTmp.NumSpec[3] = orderData[j].orderNumSpec3;
                                orderTmp.Priority = orderData[j].orderPriority;
                                orderTmp.ProductionFactor = orderData[j].orderProductionFactor;
                                orderTmp.set_Comment(1, orderData[j].Comment);
                            }
                        }

                    }

                    common.pro.UpdateAll();

                    //遍历所有的订单表，如果其中的原始订单号为订单编号的订单存在，则需要将其删除
                    AsLib.ASBOrder asbOrderRoot = common.pro.RootOrder;
                    ASOObjectList orderList=new ASOObjectList();
                    //orderList = (ASOObjectList)asbOrderRoot;
                    for (int i = 1; i <=asbOrderRoot.ChildCount; i++)
                    {
                        orderList.AddObject(i, asbOrderRoot.get_Child(i));
                    }
                    orderList.FilterByExprStr("fvalid(me.OrderUser_UERPMONO)");
                    AsLib.ASBOrder orderChild = new ASBOrderClass();
                    string[] strOrderNo = new string[asbOrderRoot.ChildCount];

                    //取得所有订单表中的原始订单号
                    for (int i = 1; i <= orderList.ObjectCount; i++)
                    {
                        orderChild =(ASBOrder) orderList.get_Object(i);
                        string orderNo = orderChild.GetAsStr((TPropertyID)Convert.ToInt32(common.GetLanguageWord("PropertyID", "OrderUser_UERPMONO")), 1);
                        for (int ii = 1; ii <=asbOrderRoot.ChildCount; ii++)
                        {
                            if (asbOrderRoot.get_ChildAsOrder(ii).Code==orderNo)
                            {
                                asbOrderRoot.DeleteChild(ii);
                                break;
                            }
                        }
                    }

                   


                    common.pro.UpdateAll();
                    asbOrderRoot = null;
                    orderChild = null;

                    if (!status || !ExStatus)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("导入Asproa时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        importFlag = 0;
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("所选数据已成功导入到Asporva中!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        importFlag = 1;
                    }

                    recCount = drs.Length;
                    //remark = "";
                    InsertLog(ref importFlag, ref recCount, remark);



                }
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                remark = ex.Message;
                InsertLog(ref importFlag, ref recCount, remark);


            }
            finally
            {
                Cursor.Current = currentCursor;
                string strSQL = " UPDATE sps SET sps.OperationProcess = 0 FROM SysProSwitch sps "
                                + " WHERE sps.ProcessType='OrderImport'  ";
                accessdb.RsChange(strSQL);
            }

        }

        //遍历所有的订单数据，找出存在原始订单号的工单数据，删除即可
        private static void DeleteOrder(ref AsLib.ASBOrder asbOrderRoot, ref AsLib.ASBOrder orderChild, string[] strOrderNo)
        {
            for (int i = 0; i < strOrderNo.Length; i++)
            {
                asbOrderRoot = common.pro.RootOrder;
                for (int j = 0; j < asbOrderRoot.ChildCount; j++)
                {
                    orderChild = asbOrderRoot.get_ChildAsOrder(j);
                    if (orderChild.GetAsStr((TPropertyID)Convert.ToInt32(common.GetLanguageWord("PropertyID", "OrderUser_UERPMONO")), 1) == strOrderNo[i])
                    {
                        asbOrderRoot.DeleteChild(j);
                        break;
                    }
                }
            }
        }

        private void InsertLog(ref int importFlag, ref int recCount, string remark)
        {

            //写入更新标志,已导入Asprova标志及日志
            string strInsertLog = " set xact_abort on begin tran "
                                + " insert into OpLog values('" + strTranNo
                                + "','Order Import'," + importFlag.ToString()
                                + ",'" + recCount.ToString() + "','"
                                + remark + "','"
                                + common._userid
                                + "',getdate(),1) "
                                + " UPDATE sps SET sps.OperationProcess = 0 FROM SysProSwitch sps "
                                + " WHERE sps.ProcessType='OrderImport'  "
                                + "  commit tran ";
            accessdb.RsChange(strInsertLog);
        }
        #endregion

        //切换用户
        private void txtChange_Click(object sender, EventArgs e)
        {
            frmLogon frmLog = new frmLogon();
            frmLog.ShowDialog();

            if (frmLog.DialogResult == DialogResult.OK)
            {
                IniDataSource();
            }
           
            frmLog.Dispose();
            frmLog = null;

        }



    }
}
